package com.hm.hall.commons.util;

import java.util.Map;

/**
 * JAVA 返回随机数，并根据概率、比率
 *
 * @author luhong
 */
public class PtRandomUtil {


    static {


    }


    /**
     * 概率获得值
     * 参数 map 例:
     * {
     * "0":"0.5", //50% 获得0
     * "1":"0.2", //20% 获得1
     * "2":"0.3",//30% 获得2
     * }
     *
     * @return key 如果不存在返回-1
     */
    public static Object percentageRandom(Map<Object, Double> map) {
        double randomNumber = Math.random();
        double minRate = 0.0, maxRate = 0.0;

        for (Object key : map.keySet()) {
            minRate = maxRate;
            maxRate = maxRate + Double.valueOf("" + map.get(key));
            if (randomNumber >= minRate && randomNumber < maxRate) {
                return key;
            }
        }
        return "-1";
    }


    /**
     * 百分比概率获得值
     * 参数 map 例:
     * [
     * [50,"0"], //50% 获得"0",
     * [20,"1"], //20% 获得"1"
     * [30,"2"], //30% 获得"2"
     * ]
     */
    public static Object percentageRandom(Object[][] map) {
        int randomNumber = (int) (Math.random() * 100);
        int minRate = 0, maxRate = 0;
        for (Object[] val : map) {
            minRate = maxRate;
            maxRate = maxRate + (int) val[0];
            if (randomNumber >= minRate && randomNumber < maxRate) {
                return val[1];
            }
        }
        return null;
    }


    /**
     * 百分比概率获得值
     * 参数 map 例:
     * [
     * [50000,"0"], //50.000% 获得"0",
     * [20000,"1"], //20.000% 获得"1"
     * [30000,"2"], //30.000% 获得"2"
     * ]
     */
    public static Object percentageHighRandom(Object[][] map) {
        int randomNumber = (int) (Math.random() * 100000);
        int minRate = 0, maxRate = 0;
        for (Object[] val : map) {
            minRate = maxRate;
            maxRate = maxRate + (int) val[0];
            if (randomNumber >= minRate && randomNumber < maxRate) {
                return val[1];
            }
        }
        return null;
    }

}

